﻿using System;
using System.Security.Cryptography;
using System.Text;
using Taxhui.Utils.IOUtils;
using Taxhui.Utils.UserModel;

namespace Taxhui.Utils.CryptUtils
{
    public static class SHACrypt
    {
        #region SHA加密
        /// <summary>
        /// SHA1加密
        /// </summary>
        /// <param name="str">原文</param>
        /// <returns></returns>
        public static string ShaCrypt(string str, SHABits enType, Encoding sEncode = null)
        {
            try
            {
                sEncode = sEncode ?? Encoding.UTF8;
                byte[] byteValue = string.IsNullOrEmpty(str) ? new byte[0] : sEncode.GetBytes(str);
                return DataUtil.ByteToStr(ShaCrypt(byteValue, enType));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static byte[] ShaCrypt(byte[] toCrypt, SHABits enType)
        {
            byte[] byteHash;
            switch (enType)
            {
                case SHABits.sha1:
                    byteHash = Sha1EnCrypt(toCrypt);
                    break;
                case SHABits.sha256:
                    byteHash = Sha256EnCrypt(toCrypt);
                    break;
                case SHABits.sha384:
                    byteHash = Sha384EnCrypt(toCrypt);
                    break;
                case SHABits.sha512:
                    byteHash = Sha512EnCrypt(toCrypt);
                    break;
                default:
                    byteHash = Sha1EnCrypt(toCrypt);
                    break;
            }
            return byteHash;
        }
        public static byte[] Sha1EnCrypt(byte[] toCrypt)
        {
            SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
            byte[] hash = SHA.ComputeHash(toCrypt);
            SHA.Clear();
            SHA.Dispose();
            return hash;
        }
        public static byte[] Sha256EnCrypt(byte[] toCrypt)
        {
            SHA256CryptoServiceProvider SHA = new SHA256CryptoServiceProvider();
            byte[] hash = SHA.ComputeHash(toCrypt);
            SHA.Clear();
            SHA.Dispose();
            return hash;
        }
        public static byte[] Sha384EnCrypt(byte[] toCrypt)
        {
            SHA384CryptoServiceProvider SHA = new SHA384CryptoServiceProvider();
            byte[] hash = SHA.ComputeHash(toCrypt);
            SHA.Clear();
            SHA.Dispose();
            return hash;
        }
        public static byte[] Sha512EnCrypt(byte[] toCrypt)
        {
            SHA512CryptoServiceProvider SHA = new SHA512CryptoServiceProvider();
            byte[] hash = SHA.ComputeHash(toCrypt);
            SHA.Clear();
            SHA.Dispose();
            return hash;
        }
        #endregion
    }
}
